package com.atguigu.oss.service.Impl;

import com.atguigu.oss.service.FileService;
import com.atguigu.oss.util.ConstantPropertiesUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file)  {
        String uploadUrl = null;
        String ossUrl = ConstantPropertiesUtil.OSS_URL;
        String accessKey = ConstantPropertiesUtil.ACCESS_KEY;
        String secretKey = ConstantPropertiesUtil.SECRET_KEY;
        String bucket = ConstantPropertiesUtil.BUCKET_NAME;
        String fileHost = "test";

        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        //获取上传文件流
        InputStream inputStream  = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        //构建日期路径：avatar/2019/02/26/文件名
        String filePath = new DateTime().toString("yyyy/MM/dd");

        String fileName = UUID.randomUUID().toString();

        String original = file.getOriginalFilename();
        String fileType = original.substring(original.lastIndexOf("."));

        String newName = fileName + fileType;
        String key = fileHost + "/" + filePath + "/" + newName;

        // 上传
        try {
            Response response = uploadManager.put(inputStream,key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            // System.out.println(putRet.key);
            //  System.out.println(putRet.hash);
            uploadUrl = ossUrl + "/"  +key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        System.out.println(uploadUrl);
        return uploadUrl;
    }
}
